package qwq.zyu.Utils;

public class NumberToChineseUtil {
    private static final String[] CHINESE_NUMS =
            {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    private static final String[] CHINESE_UNITS =
            {"", "十", "百", "千"};
    private static final String[] CHINESE_BIG_UNITS =
            {"", "万", "亿"};

    public static String intToChinese(int num) {
        if (num == 0) return "零";

        StringBuilder result = new StringBuilder();
        int unitPos = 0;  // 记录当前的单位（万、亿）
        boolean needZero = false; // 标记需要插入"零"

        while (num > 0) {
            int part = num % 10000;  // 每4位处理一次
            if (part > 0) {
                String partChinese = convertPart(part);
                if (needZero) {
                    result.insert(0, "零");
                }
                result.insert(0, partChinese + CHINESE_BIG_UNITS[unitPos]);
            } else {
                needZero = true; // 如果当前部分是 0000，可能需要零
            }
            num /= 10000;
            unitPos++;
        }
        return result.toString();
    }

    private static String convertPart(int num) {
        StringBuilder sb = new StringBuilder();
        boolean zeroFlag = false;
        int unitIndex = 0;

        while (num > 0) {
            int digit = num % 10;
            if (digit == 0) {
                if (!zeroFlag) {
                    sb.insert(0, "零");
                    zeroFlag = true;
                }
            } else {
                sb.insert(0, CHINESE_NUMS[digit] + CHINESE_UNITS[unitIndex]);
                zeroFlag = false;
            }
            num /= 10;
            unitIndex++;
        }

        String result = sb.toString();
        // 特殊情况：去掉"一十"的"一"，变成"十"
        if (result.startsWith("一十")) {
            result = result.substring(1);
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(intToChinese(123));       // 一百二十三
        System.out.println(intToChinese(1005));      // 一千零五
        System.out.println(intToChinese(10000));     // 一万
        System.out.println(intToChinese(10123));     // 一万零一百二十三
        System.out.println(intToChinese(1000000));   // 一百万
        System.out.println(intToChinese(10000123));  // 一千万零一百二十三
        System.out.println(intToChinese(0));         // 零
    }
}
